package com.linciping.useges.plugin.asyc;

import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiJavaFile;
import com.linciping.useges.plugin.bean.File2R;
import com.linciping.useges.plugin.bean.PsiFile2Content;
import com.linciping.useges.plugin.bean.Res2SourceFile;
import org.jetbrains.kotlin.psi.KtFile;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

public class ResUsegesForSourceCallable implements Callable<List<Res2SourceFile>> {

    private final List<File2R> resRList;
    private final List<PsiFile2Content> waitFindPsiFileContentList;

    public ResUsegesForSourceCallable(List<File2R> resRList, List<PsiFile2Content> waitFindPsiFileContentList) {
        this.resRList = resRList;
        this.waitFindPsiFileContentList = waitFindPsiFileContentList;
    }

    @Override
    public List<Res2SourceFile> call() {
        List<Res2SourceFile> res2SourceFileList = new ArrayList<>();
        for (File2R file2R : resRList) {
            isSpend(res2SourceFileList, file2R);
        }
        return res2SourceFileList;
    }

    private void isSpend(List<Res2SourceFile> res2SourceFileList, File2R file2R) {
        Res2SourceFile res2SourceFile;
        String resFileName = file2R.getFile().getName();
        String constantR = file2R.getConstantR();
        for (PsiFile2Content content : waitFindPsiFileContentList) {
            if (isHasSpend(content.getContent(), constantR)) {
                PsiFile psiFile = content.getPsiFile();
                if (psiFile instanceof PsiJavaFile) {
                    PsiJavaFile psiJavaFile = (PsiJavaFile) psiFile;
                    res2SourceFile = new Res2SourceFile(resFileName, constantR, psiJavaFile.getPackageName(), psiJavaFile.getName());
                    res2SourceFileList.add(res2SourceFile);
                } else if (psiFile instanceof KtFile) {
                    KtFile ktFile = (KtFile) psiFile;
                    res2SourceFile = new Res2SourceFile(resFileName, constantR, ktFile.getPackageName(), ktFile.getName());
                    res2SourceFileList.add(res2SourceFile);
                }
            }
        }
    }

    protected boolean isHasSpend(String content, String constantR) {
        return content.contains(constantR);
    }
}
